package com.hubei.controller;

import com.hubei.exception.CustomException;
import com.hubei.service.FileUploadService;
import com.hubei.service.Impl.FileUploadServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class FileController {

    @Autowired
    private FileUploadService uploadService;

    @RequestMapping("/file_upload.action")
    public String visitFile() {

        return "upload_file";
    }

    @RequestMapping("/save_upload.action")
    public String saveFile(HttpServletRequest request,MultipartFile file){
        ServletContext application = request.getSession().getServletContext();
        String realPath = application.getRealPath("/");
        realPath = realPath.replace("\\","/")+"files/";
        if (file.getSize()!=0) {
            String fileName = file.getOriginalFilename();
            String type = fileName.substring(fileName.lastIndexOf("."));
            String newName = dealTime() + UUID.randomUUID() + type;
            File saveFile = new File(realPath + newName);
            try {
                file.transferTo(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Map<String, String > map = new HashMap<>();
            map.put("name", fileName);
            map.put("path", "/files/" + newName);
            uploadService.saveFile(map);

        }else {
            throw new CustomException("没有文件数据提交！！！");
        }
        return "redirect:upload_list.action";
    }

    @RequestMapping("/upload_list.action")
    public String queryList(Model model){
        List<Map<String,String>> list = uploadService.queryList();
        model.addAttribute("fileList", list);
        return "upload_file";
    }

    private String dealTime(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
        return format.format(date);
    }

}